<?php

namespace app\admin\service;


use app\common\model\integral\IntegralProductSku;
use app\common\model\integral\IntegralProductSpec;
use app\common\model\integral\IntegralProduct;
use app\common\model\integral\IntegralProductAttribute;
use app\common\model\integral\IntegralProductClass;
use app\common\model\integral\IntegralProductClassBind;
use app\common\model\integral\IntegralProductSpecValue;
use think\facade\Db;

class IntegralProductService extends BaseService
{

    public function __construct()
    {
        $this->model = new IntegralProduct();
    }


    public function edit()
    {
        $data = request()->param();
        //标签处理
        $label_one = getter($data, 'label_one', '');
        $label_tow = getter($data, 'label_tow', '');
        if ($label_one && $label_tow) {
            $data['label'] = $label_one . '|' . $label_tow;
        } else {
            $data['label'] = ($label_one) ? $label_one : $label_tow;
        }


        $classAry = getter($data, 'class_id', []);
        if (empty($classAry)) {
            return message('分类不能为空！请填写', false);
        }

        $typeId = getter($data, 'type_id', '');
        if (empty($typeId)) {
            return message('商品类型不能为空，请选择', false);
        }


        $skuAry = getter($data, 'formdatas', []);
        if (empty($skuAry)) {
            return message('商品规格不能为空，请选择填写！', false);
        }

        foreach ($skuAry as $k => &$v) {
            $price[] = $v['price'];
            if (!$v['img']) {
                $v['img'] = $data['cover'];
                //return message('商品sku图片不能为空', false);
            }
            if (!is_numeric($v['integral_price'])) {
                return message('商品sku消耗积分不能为空', false);
            }
            if (!is_numeric($v['price'])) {
                $v['price'] = 0;
                //return message('商品sku销售价不能为空', false);

            }
            if (!is_numeric($v['stock'])) {
                return message('商品sku库存不能为空', false);
            }
        }

        $data['price'] = min($price);
        foreach ($skuAry as $k => $v) {
            if ($v['price'] == $data['price']) {
                $data['integral_price'] = $v['integral_price'];
            }
        }


        //幻灯片处理
        $covers = getter($data, 'covers', []);
        $data['covers'] = serialize($covers);

        $rowId = $this->model->edit($data);
        if ($rowId) {
            IntegralProductClassBind::productClassBin($classAry, $rowId);
            IntegralProductSku::productSkuBin($skuAry, $rowId);
            return message();
        }
        return message('错误', false);
    }


    public function getList()
    {
        $data = request()->param();

        $map = [];
        $name = getter($data, 'name', '');
        if (!empty($name)) {
            $map[] = ["name", "like", "%{$name}%"];
        }

        $classId = getter($data, 'class_id', 0);
        if ($classId > 0) {
            $productIds = IntegralProductClassBind::getClassProductIds($classId);
            $map[] = ['id', 'in', $productIds];
        }

        $isRecommend = getter($data, 'is_recommend', 0);
        if ($isRecommend > 0) {
            $map[] = ['is_recommend', '=', $isRecommend];
        }


        $classList = IntegralProductClass::where('pid', 0)->field('id,title,pid')->select()->toArray();
        $classOptions = [];
        foreach ($classList as $k => $v) {
            $classOptions[$k] = [
                'id' => $v['id'],
                'label' => $v['title'],
            ];
            $children = IntegralProductClass::where('pid', $v['id'])->field('id,title as label')->select()->toArray();
            $classOptions[$k]['children'] = ($children) ? $children : 'undefined';
        }
        $typeList = IntegralProductAttribute::where('status', 1)->field('id,title')->select()->toArray();


        $list = $this->model->where($map)->page(PAGE, PERPAGE)->order('id desc')->select();
        foreach ($list as $k => $v) {
            $label = explode('|', $v['label']);
            $list[$k]['label_one'] = (count($label) > 0) ? $label[0] : '';
            $list[$k]['label_tow'] = (count($label) > 1) ? $label[1] : '';
            $list[$k]['covers'] = unserialize($v['covers']);
            $attribute_ids = [];


            $list[$k]['type_id'] = ($v['type_id'] == 0) ? '' : $v['type_id'];
            $list[$k]['type_list'] = $typeList;
            $list[$k]['attribute_id'] = $attribute_ids;
            $list[$k]['options'] = $classOptions;
            $classData = IntegralProductClassBind::where('product_id', $v['id'])->alias('b')->join('rxthinkcmf.evt_customer_integral_product_class c', 'b.class_id = c.id')->field('group_concat(c.title) as name, group_concat(c.id) as id')->find()->toArray();


            $list[$k]['class_id'] = explode(',', $classData['id']);
            $list[$k]['class_name'] = $classData['name'];

            if ($v['type_id'] == 0) {
                $list[$k]['spec'] = [];
                $list[$k]['specCheck'] = [];
                $list[$k]['lists'] = [];
                $list[$k]['formd'] = [];
            } else {
                $list[$k]['spec'] = $this->specList($v['type_id'])->toArray();
                $skuList = IntegralProductSku::where('product_id', $v['id'])->select()->toArray();
                $skuInfoData = '';
                $sku_names = '';
                foreach ($skuList as $kl => $sku) {
                    if ($kl == 0) {
                        $skuInfoData .= $sku['data'];
                    } else {
                        $skuInfoData .= ',' . $sku['data'];
                    }
                    $sku_names .= '【' . str_replace(',', ';', $sku['name']) . '】 ';
                }

                $list[$k]['sku_names'] = $sku_names;

                $skuData = array_unique(explode(',', str_replace('-', ',', $skuInfoData)));
                $ary = [];
                if ($skuData) {
                    foreach ($skuData as $vl) {
                        $ary[] = $vl * 1;
                    }
                }
                $list[$k]['specCheck'] = $ary;
                $info = $this->getSpecValue($ary, $v['id']);
                $list[$k]['lists'] = $info['list'];
                $list[$k]['formd'] = $info['data'];
            }

        }

        //获取数据总数
        $count = $this->model->where($map)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }


    public function getClassList()
    {
        $list = IntegralProductClass::where('pid', 0)->select()->toArray();
        $data = [];
        if (count($list) > 0) {
            foreach ($list as $i => $v) {
                $children = $this->classList($v['id']);
                if ($children) {
                    $data[] = array(
                        'id' => $v['id'],
                        'label' => $v['title'],
                        'children' => $children
                    );
                } else {
                    $data[] = array(
                        'id' => $v['id'],
                        'label' => $v['title'],
                    );
                }
            }
            return message('操作成功', true, $data);
        }
        return message('请先创建商品分类,否则无法创建商品', false);
    }

    public function classList($id)
    {
        $list = IntegralProductClass::where('pid', $id)->select()->toArray();
        $data = [];
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                $children = $this->classList($v['id']);
                if ($children) {
                    $data[] = array(
                        'id' => $v['id'],
                        'label' => $v['title'],
                        'children' => $children
                    );
                } else {
                    $data[] = array(
                        'id' => $v['id'],
                        'label' => $v['title'],
                    );
                }
            }
        }
        return $data;
    }


    public function getAseSpecAttribute()
    {
        $data = request()->param();
        $id = getter($data, 'base_attribute_id', '');

        return $this->specList($id);
    }


    private function specList($base_attribute_id)
    {
        $attributeModel = IntegralProductAttribute::where('id', $base_attribute_id)->where('status', 1)->field('title,spec_ids')->find();
        $specIds = explode(',', $attributeModel['spec_ids']);
        $specList = IntegralProductSpec::where('id', 'in', $specIds)->where('status', 1)->field('title,id')->order('sort')->select();
        foreach ($specList as $k => $spec) {
            $spec->specValue;
        }
        return $specList;
    }

    public function getData()
    {
        $data = request()->param();
        $ids = getter($data, 'ids', []);
        $productId = getter($data, 'id', '');
        return $this->getSpecValue($ids, $productId);
    }

    private function getSpecValue($ids, $productId = '')
    {
        $list = IntegralProductSpecValue::where('id', 'in', $ids)->field('spec_id')->group('spec_id')->select()->toArray();

        $data = [];
        foreach ($list as $k => $v) {
            $L = IntegralProductSpecValue::where('spec_id', $v['spec_id'])->where('id', 'in', $ids)->field('id,title')->select()->toArray();
            if ($k == 0) {
                foreach ($L as $kl => $vl) {
                    $data[] = [
                        'id' => $vl['id'],
                        'title' => $vl['title'],
                    ];
                }
            } else {
                foreach ($data as $kd => $vd) {
                    foreach ($L as $kl => $vl) {
                        $data[] = [
                            'id' => $vd['id'] . '-' . $vl['id'],
                            'title' => $vd['title'] . '-' . $vl['title'],
                        ];
                    }
                }
            }
        }

        $num = count($list);
        $datas = $formdatas = [];
        foreach ($data as $k => $v) {
            if (count(explode('-', $v['id'])) == $num) {
                $datas[] = $v;
                $formdatas[$v['id']] = [
                    'img' => '',
                    'price' => '',
                    'integral_price' => '',
                    'stock' => '',
                ];
                if ($productId) {
                    $info = IntegralProductSku::where('product_id', $productId)->where('data', $v['id'])->find();
                    if ($info) {
                        $info = $info->toArray();
                        $formdatas[$v['id']] = [
                            'img' => $info['picture'],
                            'price' => $info['price'],
                            'integral_price' => $info['integral_price'],
                            'stock' => $info['stock'],
                        ];
                    }
                }
            }
        }

        return [
            'list' => $datas,
            'data' => $formdatas
        ];
    }


    public function getInfoList()
    {
        //获取分类
        $classList = IntegralProductClass::where('pid', 0)->field('id,title,pid')->select()->toArray();
        if (empty($classList)) {
            return message('请先创建商品分类！', false);
        }
        $classOptions = [];
        foreach ($classList as $k => $v) {
            $classOptions[$k] = [
                'id' => $v['id'],
                'label' => $v['title'],
            ];
            $children = IntegralProductClass::where('pid', $v['id'])->field('id,title as label')->select()->toArray();
            $classOptions[$k]['children'] = ($children) ? $children : 'undefined';
        }

        $typeList = IntegralProductAttribute::where('status', 1)->field('id,title')->select()->toArray();
        if (empty($classList)) {
            return message('请先创建商品类型！', false);
        }

        return message('操作成功', true, [
            'options' => $classOptions,
            'types' => $typeList
        ]);
    }


}